/**
 * Created by tanbingqin on 2020/12/3.
 */
import { messages } from "share/common";
/**
 * 操作：报废
 * 适用：已通过(info.status === 1003) 或者 单据已停用(info.closed === true) 的 差旅申请单
 *      从申请单列表进入的详情 登录人是申请人或制单人
 */
import React from "react";
import { connect } from "react-redux";
import menuRoute from "routes/menuRoute";
import { Form, Button, Modal, message } from "antd";
import errorMessage from "share/errorMessage";

import requestService from "containers/request/request.service";

class TravelInvalidBtn extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      showInvalidBtn: false, //是否显示【报废】按钮
    };
  }

  componentDidMount() {
    this.initShowBtn(this.props);
  }

  componentWillReceiveProps(nextProps) {
    this.initShowBtn(nextProps);
  }

  initShowBtn = (props) => {
    const { formInfo, info } = props;
    const { loginUser } = this.props;
    if (
      info.formType === 2001 &&
      (info.status === 1003 || info.closed) &&
      formInfo.customFormPropertyMap &&
      formInfo.customFormPropertyMap["application.invalid.enabled"] === "true" &&
      info.applicant &&
      (loginUser.userOID === info.applicant.userOID || loginUser.userOID === info.createdBy)
    ) {
      this.setState({ showInvalidBtn: true });
    }
  };

  handleInvalid = () => {
    Modal.confirm({
      title: messages("request-1.key894") /*是否报废该申请单*/,
      content: (
        <div>
          {
            messages(
              "request-1.key895"
            ) /*若确认报废单据后，系统将不能再重新启用，将会影响您关联报销或行程预订，若已订票需自行至消费商子应用进行退改。*/
          }
        </div>
      ),
      onOk: this.handleInvalidOk,
    });
  };

  handleInvalidOk = () => {
    this.setState({ loading: true });
    requestService
      .invalidApplication(this.props.info.applicationOID)
      .then((res) => {
        this.setState({ loading: false });
        message.success(messages("request-1.key896") /*报废单据成功*/);
        this.props.goBack(true);
      })
      .catch((err) => {
        errorMessage(err.response);
        this.setState({ loading: false });
      });
  };

  render() {
    const { loading, showInvalidBtn } = this.state;
    return (
      <div className="request-btn">
        {showInvalidBtn && (
          <Button loading={loading} onClick={this.handleInvalid}>
            {messages("request-1.key897") /*报废*/}
          </Button>
        )}
      </div>
    );
  }
}

TravelInvalidBtn.propTypes = {
  formInfo: React.PropTypes.object,
  info: React.PropTypes.object,
};

TravelInvalidBtn.contextTypes = {
  router: React.PropTypes.object,
};

function mapStateToProps(state) {
  return {
    loginUser: state.login.loginUser,
  };
}

export default connect(mapStateToProps)(TravelInvalidBtn);
